// import { getToken } from '~/utils/auth'

const getDefaultState = () => {
  return {
    cookieMaxExpires: new Date(Date.now() + 8.64e7 * 7), // cookies 过期时间 new Date(Date.now() + 120 * 1000)
    userInfo: null,
    userId: '',
    token: '',
    name: '',
    nick_name: '',
    avatar: ''
  }
}

export const state = () => getDefaultState()

export const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_NICK_NAME: (state, nick_name) => {
    state.nick_name = nick_name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

export const actions = {
  // async nuxtServerInit({ commit }) {},
  // user login
  async login({ commit, state }, userInfo) {
    const { phone, code } = userInfo
    const expires = state.cookieMaxExpires
    await this.$axios.$post('/oauth/sms', { mobile: phone.trim(), code: code }).then(response => {
      commit('SET_TOKEN', response.access_token)
      this.$cookies.set('user_token', response.access_token, { expires })
    }).catch(err => {
      console.log(err)
    })
  },

  officialAccountLogin({ commit }, open_id) {
    const expires = state.cookieMaxExpires
    console.log('expires:' + expires)
    this.$axios.$post('/oauth/newQuickLogin', { open_id: open_id }).then(response => {
      commit('SET_TOKEN', response.data.access_token)
      this.$cookies.set('user_token', response.data.access_token, { expires })
    }).catch(err => {
      console.log(err)
    })
  },

  // get user info
  async getInfo({ commit }) {
    await this.$axios.$get('/me').then(response => {
      const { id, name, avatar, nick_name } = response.data
      commit('SET_USERID', id)
      commit('SET_NAME', name)
      commit('SET_NICK_NAME', nick_name)
      commit('SET_AVATAR', avatar)
      commit('SET_USERINFO', response.data)
    })
  }
}

export const getters = {
  get(state) {
    return state
  }
}

